package com.ruoyi.system.Controller;

import cn.hutool.json.JSONUtil;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.system.service.AgroAIService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpSession; // 【重要】导入HttpSession
import java.io.IOException;
import java.util.Map;

/**
 * AgroAI 对话控制器
 */
@RestController
@RequestMapping("/agroai")
public class AgroAIController extends BaseController {

    @Autowired
    private AgroAIService agroAIService;

    // 【关键修正】移除成员变量 conversationId，改用Session管理
    // private String conversationId;

    /**
     * 1. 开启一个新对话
     * 【修正】添加HttpSession参数
     */
    @PostMapping("/start")
    public AjaxResult startConversation(HttpSession session) {
        try {
            String conversationId = agroAIService.createConversation(); // 直接获取ID
            // 【关键修正】将会话ID存入当前用户的Session中，实现多用户隔离
            session.setAttribute("agroaiConversationId", conversationId);
            return AjaxResult.success("对话已开启", conversationId);
        } catch (IOException e) {
            return AjaxResult.error("开启对话失败: " + e.getMessage());
        }
    }

    /**
     * 2. 在已开启的会话中发送消息
     * 【修正】添加HttpSession参数
     */
    @PostMapping("/send")
    public AjaxResult sendMessage(@RequestBody Map<String, String> requestData, HttpSession session) {
        // 【关键修正】从当前用户的Session中获取会话ID
        String conversationId = (String) session.getAttribute("agroaiConversationId");
        if (conversationId == null) {
            return AjaxResult.error("请先开启一个对话（调用/agroai/start）");
        }
        String userMessage = requestData.get("message");
        try {
            String aiResponse = agroAIService.sendMessage(conversationId, userMessage);
            return AjaxResult.success("发送成功", aiResponse);
        } catch (IOException e) {
            return AjaxResult.error("发送失败: " + e.getMessage());
        }
    }
}